#include "CloudSpawner.h"
#include "..\Managers\RenderManager.h"
#include "..\Engines\RenderEngine.h"


CloudSpawner::CloudSpawner(const vn::IntRect& p_spawnDimensions, float p_velocity, int p_minSpawnInterval, int p_maxSpawnInterval, unsigned int p_view, float p_layer) : 
m_spawnDimensions(p_spawnDimensions), m_velocity(p_velocity), m_targetTime(0), m_elapsedTime(0), m_minSpawnInterval(p_minSpawnInterval), m_maxSpawnInterval(p_maxSpawnInterval),
m_view(p_view), m_layer(p_layer)
{ 
	generateTargetTime();
	m_spawnDimensions.w += 1;
	m_spawnDimensions.x -= 1;
}


CloudSpawner::~CloudSpawner(void)
{
	for (auto it = m_clouds.begin(); it != m_clouds.end(); it++)
	{
		RenderManager::getSingleton().getRenderEngine()->destroySprite((*it));
	}
	m_clouds.clear();
	m_spriteIDs.clear();
}


void CloudSpawner::update(const GameTime& p_gameTime)
{
	if (!m_removeList.empty())
	{
		for (auto it = m_removeList.begin(); it != m_removeList.end(); it++)
		{
			RenderManager::getSingleton().getRenderEngine()->destroySprite((*it));
			m_clouds.remove(*it);
		}
		m_removeList.clear();
	}

	m_elapsedTime = std::min(m_elapsedTime + p_gameTime.getElapsedTimeAsMilliseconds(), m_targetTime);
	if (m_elapsedTime >= m_targetTime)
	{
		spawn();
		m_elapsedTime = 0;
	}

	if (!m_clouds.empty())
	{
		for (auto it = m_clouds.begin(); it != m_clouds.end(); it++)
		{
			((*it)->translate(m_velocity * p_gameTime.deltaTime(), 0.0f));
			if (!m_spawnDimensions.intersect(vn::IntRect(static_cast<int>((*it)->getPosition().x), static_cast<int>((*it)->getPosition().y), (*it)->getTextureRect().w, (*it)->getTextureRect().h)))
			{
				m_removeList.push_back((*it));
			}
		}
	}
}

void CloudSpawner::spawnClouds(int p_amounts)
{
	
}

inline void CloudSpawner::spawn()
{
	float yPos = vn::Random::getValue(static_cast<float>(m_spawnDimensions.y), static_cast<float>(m_spawnDimensions.y + m_spawnDimensions.h));
	std::string spriteID = m_spriteIDs[vn::Random::getValue(0, static_cast<int>(m_spriteIDs.size()))];
	vn::Sprite* cloud = RenderManager::getSingleton().getRenderEngine()->createSprite(m_view, spriteID, m_layer);
	cloud->setPosition(static_cast<float>((m_spawnDimensions.x - cloud->getTextureRect().w) + 10.0f), yPos);
	cloud->setScale(1.5f, 1.5f);
	m_clouds.push_back(cloud);
	generateTargetTime();
}

inline void CloudSpawner::generateTargetTime()
{
	m_targetTime = vn::Random::getValue(m_minSpawnInterval, m_maxSpawnInterval);
}